﻿//
// (C) Copyright 2009 Irantha Suwandarathna (iranthas@hotmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Indexes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;

namespace EffiProz.Core
{
    public class ExpressionAggregate : Expression
    {
        bool isDistinctAggregate;

        public ExpressionAggregate(int type, bool distinct, Expression e)
            : base(type)
        {
            nodes = new Expression[UNARY];
            isDistinctAggregate = distinct;
            nodes[LEFT] = e;
        }

        public ExpressionAggregate(ExpressionAggregate e)
            : base(e.opType)
        {
            isDistinctAggregate = e.isDistinctAggregate;
            nodes = e.nodes;
        }

        public override bool isSelfAggregate()
        {
            return true;
        }

        public override String getSQL()
        {

            StringBuilder sb = new StringBuilder(64);
            String left = getContextSQL(nodes.Length > 0 ? nodes[LEFT]
                                                               : null);

            switch (opType)
            {

                case OpTypes.COUNT:
                    sb.Append(' ').Append(Tokens.T_COUNT).Append('(');
                    break;

                case OpTypes.SUM:
                    sb.Append(' ').Append(Tokens.T_SUM).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.MIN:
                    sb.Append(' ').Append(Tokens.T_MIN).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.MAX:
                    sb.Append(' ').Append(Tokens.T_MAX).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.AVG:
                    sb.Append(' ').Append(Tokens.T_AVG).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.EVERY:
                    sb.Append(' ').Append(Tokens.T_EVERY).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.SOME:
                    sb.Append(' ').Append(Tokens.T_SOME).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.STDDEV_POP:
                    sb.Append(' ').Append(Tokens.T_STDDEV_POP).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.STDDEV_SAMP:
                    sb.Append(' ').Append(Tokens.T_STDDEV_SAMP).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.VAR_POP:
                    sb.Append(' ').Append(Tokens.T_VAR_POP).Append('(');
                    sb.Append(left).Append(')');
                    break;

                case OpTypes.VAR_SAMP:
                    sb.Append(' ').Append(Tokens.T_VAR_SAMP).Append('(');
                    sb.Append(left).Append(')');
                    break;

                default:
                    throw Error.runtimeError(ErrorCode.U_S0500,
                                             "ExpressionAggregate");
            }

            return sb.ToString();
        }

        public override String describe(Session session, int blanks)
        {

            StringBuilder sb = new StringBuilder(64);

            sb.Append('\n');

            for (int i = 0; i < blanks; i++)
            {
                sb.Append(' ');
            }

            switch (opType)
            {

                case OpTypes.COUNT:
                    sb.Append("COUNT ");
                    break;

                case OpTypes.SUM:
                    sb.Append("SUM ");
                    break;

                case OpTypes.MIN:
                    sb.Append("MIN ");
                    break;

                case OpTypes.MAX:
                    sb.Append("MAX ");
                    break;

                case OpTypes.AVG:
                    sb.Append("AVG ");
                    break;

                case OpTypes.EVERY:
                    sb.Append(Tokens.T_EVERY).Append(' ');
                    break;

                case OpTypes.SOME:
                    sb.Append(Tokens.T_SOME).Append(' ');
                    break;

                case OpTypes.STDDEV_POP:
                    sb.Append(Tokens.T_STDDEV_POP).Append(' ');
                    break;

                case OpTypes.STDDEV_SAMP:
                    sb.Append(Tokens.T_STDDEV_SAMP).Append(' ');
                    break;

                case OpTypes.VAR_POP:
                    sb.Append(Tokens.T_VAR_POP).Append(' ');
                    break;

                case OpTypes.VAR_SAMP:
                    sb.Append(Tokens.T_VAR_SAMP).Append(' ');
                    break;
            }

            if (nodes[LEFT] != null)
            {
                sb.Append(" arg=[");
                sb.Append(nodes[LEFT].describe(session, blanks + 1));
                sb.Append(']');
            }

            return sb.ToString();
        }

        public override EfzList resolveColumnReferences(RangeVariable[] rangeVarArray,
                int rangeCount, EfzList unresolvedSet, bool acceptsSequences)
        {

            if (unresolvedSet == null)
            {
                unresolvedSet = new ArrayListIdentity();
            }

            unresolvedSet.add(this);

            return unresolvedSet;
        }

        public override void resolveTypes(Session session, Expression parent)
        {

            for (int i = 0; i < nodes.Length; i++)
            {
                if (nodes[i] != null)
                {
                    nodes[i].resolveTypes(session, this);
                }
            }

            if (nodes[LEFT]._isParam)
            {
                throw Error.error(ErrorCode.X_42567);
            }

            dataType = SetFunction.getType(opType, nodes[LEFT].dataType);
        }

        public override bool Equals(Expression other)
        {

            if (other == this)
            {
                return true;
            }

            if (other == null)
            {
                return false;
            }

            return opType == other.opType && exprSubType == other.exprSubType
                   && isDistinctAggregate
                      == ((ExpressionAggregate)other)
                          .isDistinctAggregate && Equals(nodes, other.nodes);
        }

        public Object updateAggregatingValue(Session session, Object currValue)
        {

            if (currValue == null)
            {
                currValue = new SetFunction(opType, nodes[LEFT].dataType,
                                            isDistinctAggregate);
            }

            Object newValue = nodes[LEFT].opType == OpTypes.ASTERISK
                              ? 1
                              : nodes[LEFT].getValue(session);

            ((SetFunction)currValue).add(session, newValue);

            return currValue;
        }

        /**
         * Get the result of a SetFunction or an ordinary value
         *
         * @param currValue instance of set function or value
         * @param session context
         * @return object
         */
        public Object getAggregatedValue(Session session, Object currValue)
        {

            if (currValue == null)
            {
                return opType == OpTypes.COUNT ? (int?)0
                                               : null;
            }

            return ((SetFunction)currValue).getValue(session);
        }
    }
}
